using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml.XPath;
using newtelligence.DasBlog.Util.Html;
using Syndication.Extensibility;
using DasBlogNewsGatorPlugin.DasBlog;

namespace DasBlogNewsGatorPlugin
{
	/// <summary>
	/// Summary description for DasBlogNewsGatorPlugin.
	/// </summary>
	public class DasBlogNewsGatorPlugin : IBlogExtension
	{
		public DasBlogNewsGatorPlugin()
		{

		}

		// Name of plug-in, suitable for display to a user 
		public string DisplayName 
		{ 
			get
			{
				Version v = Assembly.GetExecutingAssembly().GetName().Version;
				return String.Format("DasBlog plug-in v{0}.{1}.{2}.{3}", v.Major, v.Minor, v.Build, v.Revision);
			}
		}
		
		public bool HasConfiguration
		{ 
			get
			{
				return true;
			}
		}
		
		// Display configuration dialog to user, if applicable 
		public void Configure(IWin32Window parent)
		{
			Config cfg = new Config();
			cfg.ShowDialog(parent);
		}

		// Return true if an editing GUI will be shown to the 
		// user when BlogItem is called. In this case, the 
		// aggregator will not display its own editing UI. 
		public bool HasEditingGUI
		{
			get
			{
				return false;
			}
		}

		public void BlogItem(IXPathNavigable rssFragment, bool edited)
		{
			if ((ConfigInfo.WeblogUrl.Length == 0) || (ConfigInfo.Username.Length == 0))
			{
				MessageBox.Show("You must configure this plug-in before its first use.");
				return;
			}

			string title = "";
			string description = "";
			string categories = "";

			XPathNavigator nav = rssFragment.CreateNavigator();
			XPathNodeIterator iterator = nav.Select("/rss/channel/item/description");
			while (iterator.MoveNext())
			{
				string temp = iterator.Current.Value;
				description += temp ;

//				temp = StripPrefixedTags(temp) + NGPlugins.Media.GetMediaString();
//
//				if (temp.IndexOf("<body xmlns=\"http://www.w3.org/1999/xhtml\">") < 0) 
//				{
//					description += "<body xmlns=\"http://www.w3.org/1999/xhtml\">" + temp ;
//					description += "</body>";
//					// The description before posting should have <body ... > and </body>
//					// it should be added after changes to the description by users
//				}
//				else 
//				{
//					description += temp ;
//				}
			}

			iterator = nav.Select("/rss/channel/item/title");
			while (iterator.MoveNext())
			{
				title = iterator.Current.Value;
			}

			iterator = nav.Select("/rss/channel/item/category");
			while (iterator.MoveNext())
			{
				if (categories.Length > 0)
					categories += ";";
				categories += iterator.Current.Value;
			}


			HtmlFormatter formatter = new HtmlFormatter();
			StringWriter writer = new StringWriter();
			formatter.Format(description, writer, new HtmlFormatterOptions(' ', 4, 80, true));
			description = writer.ToString();

			string path = ConfigInfo.WeblogUrl;
			if (!path.EndsWith("/"))
				path += "/";
			path += "EditService.asmx";

			string username = ConfigInfo.Username;
			string password = ConfigInfo.Password;

			Entry entry = new Entry();
			entry.Title = title;
			// I don't find that setting this is very usefull, so I've disabled it.
			//entry.Description = description;
			entry.Created = DateTime.Now;
			entry.Modified = DateTime.Now;
			entry.Content = description;
			entry.Categories = categories;
			
			EditService editService = new EditService();
			editService.Url = path;
			editService.ConnectionGroupName = Guid.NewGuid().ToString("N");

			try
			{
				string resp = editService.CreateEntry(entry, username, password);
			}
			catch
			{
				MessageBox.Show("An error occured posting to DasBlog. Ensure that the Edit Web Service is enabled on your DasBlog Configuration page.");
			}
		}

		public string StripPrefixedTags(string html)
		{
			Regex r = new Regex(@"<[\s]*/?\w*:[^>]*>");
			return r.Replace(html,"");
		}
	}
}
